package com.atguigu.gmall.activity.controller;

import com.atguigu.gmall.activity.redis.CacheHelper;
import com.atguigu.gmall.activity.service.SeckillGoodsService;
import com.atguigu.gmall.activity.utils.DateUtil;
import com.atguigu.gmall.common.constant.MqConst;
import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.result.ResultCodeEnum;
import com.atguigu.gmall.common.service.RabbitService;
import com.atguigu.gmall.common.util.AuthContextHolder;
import com.atguigu.gmall.common.util.MD5;
import com.atguigu.gmall.model.activity.SeckillGoods;
import com.atguigu.gmall.model.activity.UserRecode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * @author 李旭
 * @date 2021/11/1 11:09
 * @Description:
 */
@RestController
@RequestMapping("/api/activity/seckill")
public class SeckillApiController {


    @Autowired
    private SeckillGoodsService seckillGoodsService;
    @Autowired
    private RabbitService rabbitService;
    @Autowired
    private RedisTemplate redisTemplate;
    //获取秒杀频道首页数据集合
    @GetMapping("/list")
    public List<SeckillGoods> list(){
        return seckillGoodsService.list();
    }
    //获取秒杀商品详情
    //秒杀详情页面
    @GetMapping("/item/{skuId}")
    public SeckillGoods item(@PathVariable String skuId){
        return seckillGoodsService.item(skuId);
    }
    //获取抢购码或下单码
    @GetMapping("/auth/getSeckillSkuIdStr/{skuId}")
    public Result getSeckillSkuIdStr(@PathVariable String skuId, HttpServletRequest request){

        SeckillGoods seckillGoods = seckillGoodsService.item(skuId);
        //1: 商品是否审核通过的
        if(!"1".equals(seckillGoods.getStatus())){
            return Result.fail().message("商品审核不通过，不能秒杀");
        }
        //2: 商品是否还有货
        if(seckillGoods.getStockCount() <= 0){
            return Result.fail().message("商品已售完");
        }
        //3:判断此商品活动是否还在继续
        //3.1:当前时间大于等于 开始时间
        //3.2：当前时间小于结束时间
        // 开始时间 <= 当前时间 < 结束时间  活动范围之内  正在秒杀中
        Calendar calendar = Calendar.getInstance();
        Date curDate = calendar.getTime();
        Date startTime = seckillGoods.getStartTime();
        Date endTime = seckillGoods.getEndTime();
        //   结束时间 <= 当前时间
        if(DateUtil.dateCompare(endTime,curDate)){
            return Result.fail().message("此商品活动已经结束，不可以秒杀");
        }
        // 开始时间 > 当前时间
        //return Result.fail().message("此商品的活动还没有开始，不可以秒杀");
        if(!DateUtil.dateCompare(startTime,curDate)){
            return Result.fail().message("此商品的活动还没有开始，不可以秒杀");
        }
        //4:发放 抢购码
        String userId = AuthContextHolder.getUserId(request);
        String skuIdStr = MD5.encrypt(userId);
        return Result.ok(skuIdStr);
    }

    //开始抢购
    @PostMapping("/auth/seckillOrder/{skuId}")
    public Result seckillOrder(@PathVariable Long skuId,String skuIdStr,HttpServletRequest request){
//        1、校验抢购码
        String userId = AuthContextHolder.getUserId(request);
        if(StringUtils.isEmpty(skuIdStr)){
            return Result.build(null, ResultCodeEnum.SECKILL_ILLEGAL);//217, "请求不合法"
        }
        if(!skuIdStr.equals(MD5.encrypt(userId))){
            return Result.build(null, ResultCodeEnum.SECKILL_ILLEGAL);//217, "请求不合法"
        }
//        2、校验状态位
        Object status = CacheHelper.get(skuId.toString());
        if(!"1".equals(status)){
            return Result.build(null, ResultCodeEnum.SECKILL_FINISH);//213 请售完
        }

        //用户的ID   商品的ID
        UserRecode userRecode = new UserRecode();
        userRecode.setUserId(userId);
        userRecode.setSkuId(skuId);
//        3、发消息
        rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_SECKILL_USER,
                MqConst.ROUTING_SECKILL_USER,userRecode);
//        4、返回200
        return Result.ok();
    }

    //轮训查询秒杀结果
    @GetMapping("/auth/checkOrder/{skuId}")
    public Result checkOrder(@PathVariable Long skuId,HttpServletRequest request){
        String userId = AuthContextHolder.getUserId(request);
//        1、用户是否已经下单
        Object o = redisTemplate.opsForValue().get(RedisConst.SECKILL_ORDERS_USERS + userId + ":" + skuId);
        if(null != o){
            return Result.build(null,ResultCodeEnum.SECKILL_ORDER_SUCCESS);//218 下单成功
        }
        //2:校验用户是否来过
        Object o1 = redisTemplate.opsForValue().get(RedisConst.SECKILL_USER + userId + ":" + skuId);
        if(null != o1){
            //用户已经来过了
            //        3、用户是否有抢购资格
            Object o2 = redisTemplate.opsForValue().get(RedisConst.SECKILL_ORDERS + userId + ":" + skuId);
            if (null != o2) {
                //215 抢单成功
                return Result.build(null, ResultCodeEnum.SECKILL_SUCCESS);//215 抢单成功
            } else {
                return Result.build(null, ResultCodeEnum.SECKILL_FAIL);//216 抢单失败
            }
        }else{
            ////用户没来过了
            //4:校验状态位是否还有货
            Object status = CacheHelper.get(skuId.toString());
            if(!"1".equals(status)){
                return Result.build(null, ResultCodeEnum.SECKILL_FINISH);//213 请售完
            }else{
                //        5、用户排队中  211
                return Result.build(null, ResultCodeEnum.SECKILL_RUN);
            }
        }
    }
}
